package wicresoft.controller.common;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {


    public static String post(String url, Map<String, Object> dataMap) throws Exception {
        String responseMsg = null;
        //1.构造HttpClient的实例
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setContentCharset("UTF-8");
        //2.构造PostMethod的实例
        PostMethod postMethod = new PostMethod(url);
        //3.把参数值放入到PostMethod对象中
        if (dataMap != null) {
            for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    continue;
                }
                postMethod.addParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        try {
            // 4.执行postMethod,调用http接口
            httpClient.executeMethod(postMethod);
            responseMsg = new String(postMethod.getResponseBody(), "UTF-8");
        } finally {
            //7.释放连接
            postMethod.releaseConnection();
        }
        return responseMsg;
    }


    public static void main(String args[]) {

        List<String> stringList = new ArrayList<String>();

        for (String s : stringList) {
            String resutl = null;
            try {
                resutl = post(s, null);
                System.out.println(resutl);
            } catch (Exception e) {
                System.out.println(resutl);
                System.out.println(s);
                e.printStackTrace();
                break;
            }

        }

    }


}
